package myJs.user

import myJs.tool.Tool.zhInfo
import myJs.Utils._
import myJs.Implicits._

import myJs.myPkg._
import myJs.myPkg.jquery._
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.TypedTag
import scalatags.Text.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.tool.Tool
import myJs.user.MissionManage.webSocket
import shared.VarTool
import scala.scalajs.js.Dynamic.{global => g}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("SampleCompare")
object SampleCompare {

  val typeTagEmpty = List[TypedTag[String]]()
  val kind = VarTool.compareMissionStr


  @JSExport("init")
  def init = {
    $("#missionTable").bootstrapTable()
    refreshMission()
    refreshSampleSelect
    bootStrapValidator
    $("#form").bv.revalidateField("missionName")
    updateMissionSocket

  }

  @JSExport("operateFmt")
  def operateFmt: js.Function = {
    (v: js.Any, row: js.Dictionary[js.Any]) =>
      val deleteStr = a(
        title := "删除",
        cursor.pointer,
        onclick := s"SampleCompare.deleteData('" + row("id") + "')",
        target := "_blank",
        span(
          em(cls := "fa fa-close")
        )
      )

      val viewStr = a(title := "日志", onclick := s"MissionManage.viewLog('${row("id")}')", cursor.pointer,
        span(em(cls := "fa fa-file-text"))
      )

      val detailUrl = g.jsRoutes.controllers.SampleController.compareMissionDetailBefore().url.toString
      val detailStr = a(title := "详情", href := s"${detailUrl}?id=${row("id")}", cursor.pointer, target := "_blank",
        span(em(cls := "fa fa-eye"))
      )

      val state1 = if (List("success").contains(row("state"))) {
        List(detailStr)
      } else List[TypedTag[String]]()
      val state2 = if (!List("running").contains(row("state"))) {
        List(viewStr)
      } else List[TypedTag[String]]()
      val rs = state1 ::: state2 ::: List(deleteStr)
      rs.mkString("&nbsp;")

  }

  def updateMissionSocket = {
    val url = g.jsRoutes.controllers.MissionController.updateMissionSocket(kind).url.toString
    val wsUri = s"ws://${window.location.host}${url}"
    webSocket(wsUri)
  }

  @JSExport("refreshMission")
  def refreshMission(f: () => Any = () => ()) = {
    val url = g.jsRoutes.controllers.MissionController.getAllMission().url.toString
    Ajax.get(url = s"${url}?kind=${kind}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val data = xhr.responseText.toJArJDS
      $("#missionTable").bootstrapTable("load", data)
      f()
    }
  }

  @JSExport("myRun")
  def myRun = {
    val bv = jQuery("#form").data("bootstrapValidator")
    bv.validate()
    val valid = bv.isValid().toB
    if (valid) {
      val formData = new FormData(document.getElementById("form").toHTMLFormElement)
      $(":disabled").attr("disabled", false)
      val element = div(id := "content",
        span(id := "info", "正在运行",
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.SampleController.newCompareMission().url.toString
      val xhr = new XMLHttpRequest
      xhr.open("post", url)
      xhr.upload.onprogress = progressHandlingFunction
      xhr.onreadystatechange = (e) => {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          val data = xhr.response
          val rs = JSON.parse(data.toString).toJDJAn
          layer.close(index)
          val valid = rs("valid").toB
          if (valid) {
            refreshMission()
          } else {
            g.swal("Error", rs.myGet("message"), "error")
          }
        }
      }
      xhr.send(formData)
    }
  }

  def refreshSampleSelect = {
    val inputNames = List("sample1", "sample2")
    val url = g.jsRoutes.controllers.SampleController.getAllSample().url.toString
    Ajax.get(url = s"${url}").map { xhr =>
      val data = JSON.parse(xhr.responseText).toJArJDS
      val array = data.map { dict =>
        js.Dictionary("text" -> dict("id"), "id" -> dict("id"))
      }
      val options = Select2Options.dictData(array)
      inputNames.foreach { inputName =>
        Tool.getInputByName(inputName).select2(options)
        Tool.getInputByName(inputName).select2().trigger("onchange")
      }
    }
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.SampleController.missionNameCheck().url.toString
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "sample1" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "样品1不能为空！"
            ),
            "different" -> js.Dictionary(
              "field" -> "sample2",
              "message" -> "样品1不能为与样品2一致！"
            ),
          )
        ),
        "sample2" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "样品2不能为空！"
            ),
            "different" -> js.Dictionary(
              "field" -> "sample1",
              "message" -> "样品1不能为与样品2一致！"
            ),
          )
        ),
        "missionName" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "分析名称不能为空!"
            ),
            "remote" -> js.Dictionary(
              "message" -> "任务名已存在!",
              "url" -> url,
              "type" -> "POST",
              "delay" -> 1000,
              "data" -> js.Dictionary(
                "kind" -> "compare",
                "missionName" -> Tool.getInputByName("missionName").`val`(),
              )
            ),
          )
        ),


      )
    )
    g.$("#form").bootstrapValidator(dict)
  }

}
